<!-- f r o m 7 5  2 7 1  8 9 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="4" :sm="24">
                <a-form-item label="所属行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入所属行业查询" v-model="queryParam.industry"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="合同编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入合同编码查询" v-model="queryParam.contractCode"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="签约时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                    style="width: 100%"
                    :placeholder="['开始时间', '结束时间']"
                    v-model="queryParam.createTime"
                    @change="onDateChange"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入客户名称查询" v-model="queryParam.customerName"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="业务负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <!-- <a-input placeholder="请输入业务负责人查询" v-model="queryParam.businessLeader"></a-input> -->
                  <a-select
                    :disabled="disable"
                    v-model="queryParam.businessLeader"
                    allowClear
                    placeholder="选择业务负责人"
                    showSearch
                    optionFilterProp="children"
                  >
                    <a-select-option v-for="(item, index) in personList" :key="index" :value="item">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="4" :sm="24">
                  <a-button type="primary" @click="searchQuery">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
                </a-col>
              </span>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator" style="margin: 5px 0px">
          <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
          <a-button @click="alertExport" type="primary" icon="download">导出</a-button>
          <a-dropdown
            :trigger="['click']"
            style="margin-bottom: 10px"
            v-model="DropdownVisible"
            @visibleChange="visibleChange()"
          >
            <a-menu slot="overlay">
              <a-menu-item v-for="(item, index) in columns" :key="index"
                ><a-checkbox
                  :checked="item.show"
                  @change="
                    e => {
                      columnsCheck(e.target.checked, columns, index)
                    }
                  "
                  >{{ item.title }}</a-checkbox
                ></a-menu-item
              >
            </a-menu>
            <a-button style="margin-left: 8px"> 筛选列 <a-icon type="down" /> </a-button>
          </a-dropdown>
        </div>
        <!-- table区域-begin -->
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="
              columns.filter((col, num) => {
                if (col.show) {
                  return col
                }
              })
            "
            :dataSource="dataSource"
            :pagination="ipagination"
            :scroll="{ x: 1600, y: 1000 }"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            @change="handleTableChange"
          >
            <span slot="mx" slot-scope="text, record"> <a @click="handlEpayment(record)">付款明细</a></span>
            <span slot="az" slot-scope="text, record"> <a @click="handleEditInstall(record)">安装信息</a></span>
            <span slot="remark" slot-scope="text, record">
              <a-tooltip>
                <template slot="title">
                  {{ record.remark }}
                </template>
                <div>{{ record.remark | ellipsis(5) }}</div>
              </a-tooltip></span
            >
            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            <span slot="productList" slot-scope="text, record">
              <div v-for="(item, index) in record.productList" :key="index">
                <a-popover :title="item.name">
                  <template slot="content">
                    <p>产品单位：{{ item.unit }}</p>
                    <p>产品数量：{{ item.count }}</p>
                    <p>产品规格：{{ item.specification }}</p>
                  </template>
                  <a-tag color="cyan" style="cursor: pointer;float:left">
                    {{ item.name | ellipsis(2) }}
                  </a-tag>
                </a-popover>
              </div>
            </span>
            <span slot="contractType" slot-scope="text, record">
              <a-tooltip>
                <template slot="title">
                  <div v-if="record.contractSecondType">{{ record.contractSecondType }}</div>
                </template>
                <div v-if="record.contractType == '其他订单'" style="color:blue">{{ record.contractType }}</div>
                <div v-else>{{ record.contractType }}</div>
              </a-tooltip>
            </span>
            <span slot="contractAmount" slot-scope="text, record">
              <div style="color:Orange;cursor: pointer;font-weight:800" @click="editAmount(record)">
                {{ record.contractAmount }}
              </div>
            </span>
            <span slot="isInvoiced" slot-scope="text, record">
              <div v-for="(item, index) in isTrue" :key="index">
                {{ record.isInvoiced == item.id ? item.name : '' }}
              </div>
            </span>
            <span slot="createTime" slot-scope="text, record">
              <div>{{ $moment(record.createTime).format('YYYY-MM-DD') }}</div>
            </span>
            <span slot="earlyWarningDate" slot-scope="text, record">
              <div
                v-if="
                  0 <= $moment(record.earlyWarningDate).diff($moment(new Date()), 'days') &&
                    $moment(record.earlyWarningDate).diff($moment(new Date()), 'days') < 7
                "
                style="color:red"
              >
                {{ record.earlyWarningDate }}
              </div>
              <div v-else>{{ record.earlyWarningDate }}</div>
            </span>
            <span slot="termOfPayment" slot-scope="text, record">
              <a-tooltip>
                <template slot="title">
                  {{ record.termOfPayment }}
                </template>
                <div>{{ record.termOfPayment | ellipsis(8) }}</div>
              </a-tooltip>
            </span>
            <span slot="customerName" slot-scope="text, record">
              <a-tooltip>
                <template slot="title">
                  {{ record.customerName }}
                </template>
                <div>{{ record.customerName | ellipsis(10) }}</div>
              </a-tooltip>
            </span>
            <span slot="contractNum" slot-scope="text, record">
              <a-tooltip>
                <template slot="title">
                  {{ record.contractNum }}
                </template>
                <div>{{ record.contractNum | ellipsis(11) }}</div>
              </a-tooltip>
            </span>
            <span slot="logistics" slot-scope="text, record">
              <a-tag color="#87d068" @click="handleEditLogistics(record)">
                <a>物流信息</a>
              </a-tag>
            </span>
            <span slot="contractPdf" slot-scope="text, record">
              <a @click="myhandleExportXls(record)">下载</a>
              <a-divider type="vertical" />
              <a @click="previewFile(record)">预览</a>
            </span>
            <!-- 状态渲染模板 -->
            <template slot="customRenderFlag" slot-scope="enabled">
              <a-tag v-if="enabled" color="green">启用</a-tag>
              <a-tag v-if="!enabled" color="orange">禁用</a-tag>
            </template>
          </a-table>
          <div id="total">
            <span>合同额合计：{{ TotalAmountData.contractTotal }}</span>
            <span>已收合计：{{ TotalAmountData.contractReceived }}</span>
            <span>未收合计：{{ TotalAmountData.uncollectedTotal }}</span>
            <span>开票金额合计：{{ TotalAmountData.invoicedTotal }}</span>
          </div>
        </div>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <EditAmount ref="modalFormEditAmount" @ok="modalFormOk" @close="close"></EditAmount>
        <Contract-logistics ref="modalFormLogistics" @ok="modalFormOk"></Contract-logistics>
        <ContractEpayment ref="modalFormEpayment" @ok="modalFormOk" @close="close"></ContractEpayment>
        <Contract-install ref="modalFormInstall" @ok="modalFormOk"></Contract-install>
        <Contract-details ref="modalForm" @ok="modalFormOk"></Contract-details>
        <AlertExport ref="modalFormAlertExport" @ok="modalFormOk"></AlertExport>
      </a-card>
    </a-col>
  </a-row>
</template>
<!-- BY cao_yu_li -->
<script>
import EditAmount from './modules/EditAmount'
import { postAction } from '@api/manage'
import Vue from 'vue'
import { USER_LOGIN_NAME, USER_ID } from '@/store/mutation-types'
import AlertExport from './modules/AlertExport'
import ContractInstall from './modules/ContractInstall'
import ContractLogistics from './modules/ContractLogistics'
import ContractEpayment from './modules/ContractEpayment'
import ContractDetails from './modules/ContractDetails'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getActionImg, downFile, getAction } from '@/api/manage'
import { personList } from '@/api/api'
import { openDownloadDialog, sheet2blob } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
export default {
  name: 'CustomerList',
  mixins: [JeecgListMixin],
  components: {
    ContractLogistics,
    ContractInstall,
    ContractDetails,
    JDate,
    AlertExport,
    ContractEpayment,
    EditAmount
  },
  data() {
    return {
      disable: false,
      personList: [],
      labelCol: {
        span: 5
      },
      wrapperCol: {
        span: 18,
        offset: 1
      },
      isTrue: [
        {
          id: 0,
          name: '未开票'
        },
        {
          id: 1,
          name: '开票'
        }
      ],
      isShow: [],
      TotalAmountData: '',
      DropdownVisible: false, //选择checkbox后不收回菜单
      // 查询条件
      queryParam: {},
      ipagination: {
        pageSizeOptions: ['10', '20', '30', '100', '200']
      },
      // 表头
      columns: [
        {
          title: '录入时间',
          key: '1',
          dataIndex: 'createTime',
          width: 90,
          align: 'center',
          fixed: 'left',
          show: true,
          scopedSlots: { customRender: 'createTime' }
        },
        { title: '所属行业', key: '2', dataIndex: 'industry', width: 110, align: 'center', fixed: 'left', show: true },
        {
          title: '客户名称',
          key: '3',
          dataIndex: 'customerName',
          width: 120,
          align: 'center',
          fixed: 'left',
          show: true,
          scopedSlots: { customRender: 'customerName' }
        },
        {
          title: '内部合同编码',
          key: '4',
          dataIndex: 'contractCode',
          width: 120,
          align: 'center',
          fixed: 'left',
          show: true,
          sorter: true
        },
        {
          title: '合同编号',
          key: '5',
          dataIndex: 'contractNum',
          width: 120,
          align: 'center',
          fixed: 'left',
          show: true,
          scopedSlots: { customRender: 'contractNum' }
        },
        {
          title: '合同性质',
          key: '30',
          dataIndex: 'contractType',
          width: 90,
          align: 'center',
          show: true,
          scopedSlots: { customRender: 'contractType' }
        },
        {
          title: '产品信息',
          key: '6',
          dataIndex: 'productList',
          width: 140,
          align: 'center',
          show: true,
          scopedSlots: { customRender: 'productList' }
        },
        {
          title: '合同总金额(可修改)',
          key: '11',
          dataIndex: 'contractAmount',
          width: 90,
          align: 'center',
          show: true,
          scopedSlots: { customRender: 'contractAmount' }
        },
        { title: '已收金额', key: '12', dataIndex: 'receivedAmount', width: 90, align: 'center', show: true },
        { title: '未收金额', key: '13', dataIndex: 'uncollectedAmount', width: 90, align: 'center', show: true },
        {
          title: '是否开票',
          key: '14',
          dataIndex: 'isInvoiced',
          width: 90,
          align: 'center',
          show: false,
          scopedSlots: { customRender: 'isInvoiced' }
        },
        { title: '开票金额', key: '15', dataIndex: 'invoicedAmount', width: 90, align: 'center', show: false },
        {
          title: '付款条件',
          key: '16',
          dataIndex: 'termOfPayment',
          width: 150,
          align: 'center',
          show: true,
          scopedSlots: { customRender: 'termOfPayment' }
        },
        {
          title: '到期付款预警',
          key: '17',
          dataIndex: 'earlyWarningDate',
          width: 110,
          align: 'center',
          show: true,
          scopedSlots: { customRender: 'earlyWarningDate' }
        },
        { title: '到期付款金额', key: '23', dataIndex: 'earlyWarningAmount', width: 90, align: 'center', show: false },
        { title: '订单套数', key: '18', dataIndex: 'setOfOrders', width: 90, align: 'center', show: false },
        { title: '面积', key: '19', dataIndex: 'area', width: 90, align: 'center', show: false },
        { title: '签约时间', key: '20', dataIndex: 'signedDate', width: 90, align: 'center', show: true },
        { title: '合同进度', key: '25', dataIndex: 'contractSchedule', width: 90, align: 'center', show: false },
        { title: '业务负责人', key: '26', dataIndex: 'businessLeader', width: 90, align: 'center', show: true },
        { title: '贵金属价格', key: '27', dataIndex: 'preciousMetal', width: 90, align: 'center', show: false },
        {
          title: '物流信息',
          key: '28',
          dataIndex: 'logistics',
          width: 100,
          align: 'center',
          fixed: 'right',
          show: true,
          scopedSlots: { customRender: 'logistics' }
        },
        {
          title: '合同附件',
          key: '29',
          dataIndex: 'contractPdf',
          width: 100,
          align: 'center',
          fixed: 'right',
          show: true,
          scopedSlots: { customRender: 'contractPdf' }
        },
        {
          title: '付款明细',
          dataIndex: 'mx',
          width: 100,
          align: 'center',
          fixed: 'right',
          show: true,
          scopedSlots: { customRender: 'mx' }
        },
        {
          title: '安装信息',
          dataIndex: 'az',
          width: 100,
          align: 'center',
          fixed: 'right',
          show: true,
          scopedSlots: { customRender: 'az' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 100,
          align: 'center',
          fixed: 'right',
          show: true,
          scopedSlots: { customRender: 'remark' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          align: 'center',
          fixed: 'right',
          show: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/contractdetails/page',
        TotalAmount: '/contractdetails/getContractAmountStatics',
        delete: '/contractdetails/remove',
        deleteBatch: '/supplier/deleteBatch',
        importExcelUrl: '/supplier/importCustomer',
        exportXlsUrl: '/systemConfig/static',
        batchSetStatusUrl: '/supplier/batchSetStatus'
      }
    }
  },
  //文字溢出隐藏
  filters: {
    ellipsis(val, length) {
      if (val) {
        if (val.length > length) {
          return val.substring(0, length) + '...'
        } else {
          return val
        }
      }
    }
  },
  mounted() {
    //底部金额统计
    this.TotalAmount()
    //筛选列配置
    this.screen()
    //获取登录信息
    this.getUserDetail()
    //判断全部还是个人数据
    this.filterData()
    personList().then(res => {
      if (res.code == 200 || res.code == 10000) {
        this.personList = res.data
      } else {
        this.$message.warning(res.message)
      }
    })
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
    }
  },
  methods: {
    handleTableChange(page, filters, sorter) {
        console.log(this.order,sorter.order)
            if (sorter.order == 'ascend') {
                this.queryParam.order = 0 //正序
            } else if (sorter.order == 'descend') {
                this.queryParam.order = 1 //倒序
            } else {
                this.queryParam.order = 0 //正序
            }
            
            if (page && page.current) {
                this.ipagination = page;
                this.loadData()
                this.TotalAmount()
            }else{
              this.searchQuery()  
            }
            

    },
    filterData() {
      let a = JSON.parse(sessionStorage.getItem('UserMessage'))
      let useMsg = JSON.parse(sessionStorage.getItem('User'))
      if (a) {
        this.queryParam.businessLeader = useMsg.ename
        this.disable = true
      } else {
        this.disable = false
      }
    },
    getUserDetail() {
      getAction('/user/getUserCache').then(res => {
        console.log(res, '111111')
      })
    },
    //筛选列配置
    screen() {
      let params = {
        module: '合同明细',
        userId: Vue.ls.get(USER_LOGIN_NAME)
      }
      getAction('/fieldFilter', params).then(res => {
        if (res.code == 10000) {
          if (res.data.fieldFilter) {
            let fieldFilter = JSON.parse(res.data.fieldFilter)
            this.columns.map(item => {
              fieldFilter.map(i => {
                if (item.title == i.title) {
                  item.show = i.show
                }
              })
            })
            let i = 0
            this.columns.map(item => {
              if (item.show) {
                i++
              }
            })
            //待优化--
            this.columns.map(item => {
              if (i <= 16) {
                item.fixed = false
                console.log(i, 'x')
              } else if (i > 15) {
                if (item.key && Number(item.key) < 6) {
                  item.fixed = 'left'
                } else if (item.width == 100) {
                  item.fixed = 'right'
                }
              }
            })
            console.log(i, 'i')
          }
        }
        console.log(res, 'xxxxx')
      })
    },
    //弹出导出列表
    alertExport() {
      this.$refs.modalFormAlertExport.edit()
      this.$refs.modalFormAlertExport.title = '导出列表'
      this.$refs.modalFormAlertExport.disableSubmit = false
      if (this.btnEnableList.indexOf(1) === -1) {
        this.$refs.modalFormAlertExport.isReadOnly = true
      }
    },
    //编辑总金额
    editAmount(record) {
      this.$refs.modalFormEditAmount.edit(record)
      this.$refs.modalFormEditAmount.title = '修改总金额'
      this.$refs.modalFormEditAmount.disableSubmit = false
      if (this.btnEnableList.indexOf(1) === -1) {
        this.$refs.modalFormEditAmount.isReadOnly = false
      }
    },
    //筛选表的列
    columnsCheck(checked, data, index) {
      data[index].show = checked
      let i = 0
      data.map(item => {
        if (item.show) {
          i++
        }
      })
      //待优化--
      data.map(item => {
        if (i <= 16) {
          item.fixed = false
          console.log(i, 'x')
        } else if (i > 15) {
          if (item.key && Number(item.key) < 6) {
            item.fixed = 'left'
          } else if (item.width == 100) {
            item.fixed = 'right'
          }
        }
      })
      console.log(i, 'i')
    },
    //visibleChange
    visibleChange() {
      let a = []
      if (!this.DropdownVisible) {
        this.columns.map(item => {
          a.push({ title: item.title, show: item.show })
        })
        let params = { userId: Vue.ls.get(USER_LOGIN_NAME), module: '合同明细', fieldFilter: JSON.stringify(a) }
        postAction('/fieldFilter', params).then(res => {
          console.log(res, 'res')
        })
      }
      //  Vue.ls.get(USER_ID)
      // console.log(Vue.ls.get(USER_LOGIN_NAME))
      console.log(JSON.stringify(a), 'xxxx')
      //发送给后端 params
    },
    //记录筛选项
    getChecked() {
      //遍历后端给的数据与columns通过title进行对比改变show的状态
    },
    //初始化获取总金额
    TotalAmount() {
      let params = this.queryParam
      getAction(this.url.TotalAmount, params).then(res => {
        if (res.code === 200 || res.code === 10000) {
          this.$nextTick(() => {
            this.TotalAmountData = res.data
          })
        }
      })
    },
    close() {
      this.searchReset()
    },
    //付款明细弹窗
    handlEpayment(record) {
      this.$refs.modalFormEpayment.edit(record)
      this.$refs.modalFormEpayment.title = '付款明细'
      this.$refs.modalFormEpayment.disableSubmit = false
      if (this.btnEnableList.indexOf(1) === -1) {
        this.$refs.modalFormEpayment.isReadOnly = true
      }
    },
    //文件下载
    myhandleExportXls(record) {
      if (!record.contractPdf) {
        this.$message.warning('合同附件未上传')
      }
      downFile(this.url.exportXlsUrl + '/' + record.contractPdf).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), record.contractPdf)
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', record.contractPdf)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    //PDF预览
    previewFile(record) {
      if (record && record.contractPdf) {
        let params = record.contractPdf
        getActionImg('systemConfig/preview/' + params).then(res => {
          const binaryData = []
          binaryData.push(res)
          window.open(window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' })))
        })
      } else {
        this.$message.warning('合同附件未上传')
      }
    },
    onDateChange: function(value, dateString) {
      this.queryParam.startTime = dateString[0]
      this.queryParam.endTime = dateString[1]
      console.log(this.queryParam)
    },
    searchQuery() {
      this.loadData(1)
      this.TotalAmount()
    },
    searchReset() {
      this.queryParam = {}
      this.TotalAmount()
      this.loadData(1)
    },
    handleEdit: function(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
      if (this.btnEnableList.indexOf(1) === -1) {
        this.$refs.modalForm.isReadOnly = false
      }
    },
    handleEditInstall: function(record) {
      this.$refs.modalFormInstall.edit(record)
      this.$refs.modalFormInstall.title = '安装信息'
      this.$refs.modalFormInstall.disableSubmit = false
      if (this.btnEnableList.indexOf(1) === -1) {
        this.$refs.modalFormInstall.isReadOnly = true
      }
    },
    handleEditLogistics: function(record) {
      this.$refs.modalFormLogistics.edit(record)
      this.$refs.modalFormLogistics.title = '物流信息'
      this.$refs.modalFormLogistics.disableSubmit = false
      if (this.btnEnableList.indexOf(1) === -1) {
        this.$refs.modalFormLogistics.isReadOnly = true
      }
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
/** Button按钮间距 */
.table-operator .ant-btn {
  margin: 0 8px 8px 0;
}
#total span {
  margin-left: 20px;
  margin-right: 150px;
  font-size: 18px;
  font-weight: 600;
}
</style>
